import { HttpError, toSuccess, useEntityManager } from "@sker/core"
import { AutoUser, KsDevice } from "@sker/entities"
import { useData } from "@sker/runtime"

import { z } from "zod"

export default async () => {
    const input = z.object({
        uuid: z.string()
    })
    const body = input.parse(useData())
    const user = await useEntityManager(async m => {
        const device = await m.findOne(KsDevice, { where: { uuid: body.uuid } })
        if (!device) {
            throw new HttpError(`参数有误`)
        }
        if (!device.owner) {
            throw new HttpError(`参数有误`)
        }
        const user = await m.findOne(AutoUser, { where: { mobile: device.owner } })
        if (!user) throw new HttpError(`用户不存在或已删除`)
        const userSetting = user.setting;
        const hours = userSetting.hours || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
        const hour = new Date().getHours()
        if (hours.includes(hour)) {
            return { status: userSetting.status }
        }
        return {
            status: `stop`
        }
    })
    return toSuccess(user)
}